import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import userStore from '@/store/user'

// 静态路由 + 动态路由占位符
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Layout',
    redirect: '/home',
    component: () => import('../views/index.vue'),
    meta: {
      isDelete: false
    },
    children: [
      {
        path: '/home',
        name: 'Home',
        component: () => import('../views/home/index.vue'),
        meta: {
          title: '首页',
          isDelete: false
        }
      },
      {
        path: '/userInfo',
        name: 'UserInfo',
        component: () => import('../components/user/UserInfo.vue'),
        meta: {
          title: '用户信息',
          isDelete: false
        }
      },
      // 动态路由将插入此处（初始为空）
      // 后续通过 router.addRoute() 添加
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login.vue'),
    meta: {
      title: '登录',
      isDelete: false
    }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/error/404.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const hasToken = userStore.state.token
  if (to.path === '/login') {
    next()
  } else {
    if (hasToken) {
        next();
    } else {
      next('/login')
    }
  }
})

export default router